import React from 'react';
import { TContainerProps } from './Types';
import { V } from './containers';
import { Img } from './Img';
import { Inter } from './Texts';

export interface TAvatarProps extends TContainerProps {
  /**
   * 头像图片源
   */
  src?: string;
  /**
   * 头像大小
   */
  size?: 'small' | 'medium' | 'large' | 'xlarge';
  /**
   * 头像形状
   */
  shape?: 'circle' | 'square' | 'rounded';
  /**
   * 用户名称（用于生成默认头像）
   */
  name?: string;
  /**
   * 默认头像背景色
   */
  backgroundColor?: string;
  /**
   * 是否显示边框
   */
  bordered?: boolean;
  /**
   * 边框颜色
   */
  borderColor?: string;
  /**
   * 边框宽度
   */
  borderWidth?: number;
}

export function Avatar({
  src,
  size = 'medium',
  shape = 'circle',
  name,
  backgroundColor = '#0ea5e9',
  bordered = false,
  borderColor = '#e2e8f0',
  borderWidth = 2,
  ...props
}: TAvatarProps) {
  const sizeValue = getSizeValue(size);
  const borderRadius = getBorderRadius(shape, sizeValue);
  const avatarStyle = getAvatarStyle(
    sizeValue,
    borderRadius,
    bordered,
    borderColor,
    borderWidth
  );

  const renderContent = () => {
    if (src) {
      return (
        <Img
          src={src}
          wh={sizeValue}
          br={borderRadius}
          rm="cover"
          style={{ width: sizeValue, height: sizeValue, borderRadius }}
        />
      );
    }

    // 生成默认头像
    const initials = getInitials(name || 'U');
    return (
      <V
        wh={sizeValue}
        br={borderRadius}
        bg={backgroundColor}
        ai="c"
        jc="c"
        {...props}
      >
        <Inter fs={getFontSize(size)} fw="600" c="#ffffff">
          {initials}
        </Inter>
      </V>
    );
  };

  return <V {...avatarStyle}>{renderContent()}</V>;
}

function getSizeValue(size: string): number {
  const sizes = {
    small: 32,
    medium: 48,
    large: 64,
    xlarge: 96,
  };
  return sizes[size as keyof typeof sizes];
}

function getBorderRadius(shape: string, size: number): number {
  if (shape === 'circle') {
    return size / 2;
  } else if (shape === 'rounded') {
    return size * 0.2;
  }
  return 0;
}

function getFontSize(size: string): number {
  const fontSizes = {
    small: 12,
    medium: 16,
    large: 20,
    xlarge: 24,
  };
  return fontSizes[size as keyof typeof fontSizes];
}

function getAvatarStyle(
  size: number,
  borderRadius: number,
  bordered: boolean,
  borderColor: string,
  borderWidth: number
) {
  const style: any = {
    width: size,
    height: size,
    borderRadius,
    overflow: 'hidden',
  };

  if (bordered) {
    style.borderWidth = borderWidth;
    style.borderColor = borderColor;
  }

  return style;
}

function getInitials(name: string): string {
  if (!name) return 'U';

  const words = name.trim().split(' ');
  if (words.length === 1) {
    return words[0].charAt(0).toUpperCase();
  }

  return (words[0].charAt(0) + words[words.length - 1].charAt(0)).toUpperCase();
}
